package com.zhijiang.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.zhijiang.hospital.entity.Checkin;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 75936
 * @version 1.0
 * @project zhijiang_hospital_datas
 * @description
 * @date 2023-04-07 14:45:01
 */
@Slf4j
public class HttpUtil {
    public static final String CorpId = "ww30de27d5efb6a9db";//替换成自己的企业ID
    public static final String CorpSecret = "svUTeBOxvOq_4PudJhfXYmjqwbHqfSwuQeAPOTjUOyU";//替换成打卡应用的secret
    public static final String mailList = "Ox6GMcyHCDXKiRgfR2kE_4XIbSN7kjlqtWQ_TOXL0ig";
    public static final String GetToken = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
    public static final String GetCheckinData = "https://qyapi.weixin.qq.com/cgi-bin/checkin/getcheckindata";
    public static final String dept = "https://qyapi.weixin.qq.com/cgi-bin/department/list";
    public static final String GetUserList = "https://qyapi.weixin.qq.com/cgi-bin/user/simplelist";
    public static final Integer MAX_NUM = 100;//企业微信打卡每次最多取100条记录
    public static final String getToken = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?Corpid=" + CorpId + "&Corpsecret=" + CorpSecret + "";
    public static final String getToken1 = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?Corpid=" + CorpId + "&Corpsecret=";
    public static final String T = "Ox6GMcyHCDXKiRgfR2kE_4XIbSN7kjlqtWQ_TOXL0ig";//替换成打卡应用的secret
    private static OkHttpClient client = new OkHttpClient().newBuilder()
            .callTimeout(10, TimeUnit.SECONDS)
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .build();

    /***
     * @description:发送Get请求
     * @author: JunFu
     * @date: now
     * @param: 请求路径
     * @return: 数据字符串
     **/
    public static String get(String url) {
        Response execute = null;
        Request request = new Request.Builder()
                .method("GET", null)
                .url(url)
                .build();
        try {
            execute = client.newCall(request).execute();
            if (ObjectUtil.isNotNull(execute) && execute.isSuccessful()) {
                return execute.body().string();
            }
        } catch (IOException e) {
            log.error("http get 请求失败--{}", e);
        }
        return null;
    }

    public static byte[] getBytes(String url) {
        Response execute = null;
        Request request = new Request.Builder()
                .method("GET", null)
                .url(url)
                .build();
        try {
            execute = client.newCall(request).execute();
            if (ObjectUtil.isNotNull(execute) && execute.isSuccessful()) {
                return execute.body().bytes();
            }
        } catch (IOException e) {
            log.error("http get 请求失败--{}", e);
        }
        return null;
    }

    /***
     * @description:发送Post请求
     * @author: JunFu
     * @date:
     * @param: 请求路径 请求参数
     * @return: 字符串响应
     **/
    public static String post(String url, String body) {
        Response execute = null;
        Request request = new Request.Builder()
                .method("POST", RequestBody.create(body, MediaType.get("application/json")))
                .url(url)
                .build();
        try {
            execute = client.newCall(request).execute();
            if (ObjectUtil.isNotNull(execute) && execute.isSuccessful()) {
                return execute.body().string();
            }
        } catch (IOException e) {
            log.error("http post 请求失败--{}", e);
        }
        return null;
    }


    public static String doPost(String sendUrl, JSONObject body) {
        OutputStreamWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        HttpURLConnection conn = null;
        try {
            URL url = new URL(sendUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            //发送POST请求必须设置为true
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //设置连接超时时间和读取超时时间
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(10000);
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Accept", "application/json");
            //获取输出流
            out = new OutputStreamWriter(conn.getOutputStream());
            out.write(body.toJSONString());
            out.flush();
            out.close();
            //取得输入流，并使用Reader读取
            if (200 == conn.getResponseCode()) {
                in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
                String line;
                while ((line = in.readLine()) != null) {
                    result.append(line);
                    System.out.println(line);
                }
            } else {
                System.out.println("ResponseCode is an error code:" + conn.getResponseCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
        return result.toString();
    }

    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        List<String> idList = new ArrayList<>();
        String accessToken = JSONObject.parseObject(get(getToken)).getString("access_token");
        JSONArray userList = JSONObject.parseObject(get(GetUserList + "?access_token=" + accessToken + "&department_id=1&fetch_child=1")).getJSONArray("userlist");
        for (int i = 0; i < userList.size(); i++) {
            JSONObject userData = userList.getJSONObject(i);
            String userid = userData.getString("userid");
            map.put(userid, userData.getString("name"));
            idList.add(userid);
        }
        JSONObject body = new JSONObject();
        for (int i = 0; i < idList.size(); i += HttpUtil.MAX_NUM) {
            List<String> userIdList = idList.subList(i, i + HttpUtil.MAX_NUM > idList.size() ? idList.size() : i + HttpUtil.MAX_NUM);
            body.put("opencheckindatatype", "3");
            body.put("starttime", DateUtil.beginOfDay(new Date()).getTime() / 1000);
            body.put("endtime", DateUtil.endOfDay(new Date()).getTime() / 1000);
            body.put("useridlist", userIdList);
            JSONObject jsonObject = JSONObject.parseObject(HttpUtil.doPost(HttpUtil.GetCheckinData + "?access_token=" + accessToken, body));
            JSONArray checkinData = jsonObject.getJSONArray("checkindata");
            for (int j = 0; j < checkinData.size(); j++) {
                Checkin checkin = new Checkin();
                checkin.setCode(IdWorker.getTimeId());
                JSONObject data = checkinData.getJSONObject(j);
                checkin.setUserid(data.getString("userid"));
                checkin.setClockType(data.getString("checkin_type"));
                checkin.setLocationDetail(data.getString("location_detail"));
                checkin.setLat(data.getString("lat"));
                checkin.setLng(data.getString("lng"));
                checkin.setName(map.get(data.getString("userid")));
                checkin.setCheckinTime(DateUtil.now());
                checkin.setLocationTitle(data.getString("location_title"));
                checkin.setCheckinDate(DateUtil.date(data.getLong("checkin_time") * 1000));
                System.out.println(checkin);
            }
        }
    }


}
